var username,secretkey;
var isjump = 0;//控制翻页
var layer,$,laydate,upload,element,form,loadmsg,kj_id;
var Prize_img;	//奖品图片
var kanj_img;	//砍价图片
var alertmsg="修改";
var gl = "";
layui.config({

}).use(['form','laydate', 'layer', 'element','upload'],function(){
	form = layui.form;
	layer = layui.layer;
	$ = layui.jquery;
   // laydate = layui.laydate;//日期
    upload = layui.upload;//上传
    element = layui.element; //元素操作
	username = $.session.get("username");
	secretkey = $.session.get("user_secretkey");
	kj_id = $.session.get("kanjia_id");	//砍价商品ID
	if(kj_id==undefined ||kj_id==null ||kj_id==""){
		 kj_id = 0;
		 alertmsg="添加";
	}else{
		initdatas();
	}
	//上传奖品图片
    var uploadInst = upload.render({
		elem: '#uploadimgs'
		,url: '../../../../UploadServlet?serialtype=advimg'
		,size: 150
		,before: function(obj){
		  //预读本地文件示例，不支持ie8
		  obj.preview(function(index, file, result){
			$("#Prize_img").css("display","block");
			$('#preview').attr('src', result); //图片链接（base64）

		  });
		}
		,done: function(res){
			console.log("res====="+JSON.stringify(res));
		  //如果上传失败
		  if(res.code > 0){
			return layer.msg('上传失败');
		  }
		  Prize_img = res.data[0].src;
		}
		,error: function(){
		  //演示失败状态，并实现重传
			var demoText = $('#demoText');
			demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn  demo-reload">重试</a>');
			demoText.find('.demo-reload').on('click', function(){
			uploadInst.upload();
		  });
		}
	 });

	//上传砍价图片
	 var uploadInst2 = upload.render({
		elem: '#uploadimgs2'
		,url: '../../../../UploadServlet?serialtype=advimg'
		,size: 150
		,before: function(obj){
		  //预读本地文件示例，不支持ie8
		  obj.preview(function(index, file, result){
			$("#kanj_img").css("display","block");
			$('#preview2').attr('src', result); //图片链接（base64）

		  });
		}
		,done: function(res){
			console.log("res====="+JSON.stringify(res));
		  //如果上传失败
		  if(res.code > 0){
			return layer.msg('上传失败');
		  }
		  kanj_img = res.data[0].src;
		}
		,error: function(){
		  //演示失败状态，并实现重传
			var demoText = $('#demoText2');
			demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn  demo-reload">重试</a>');
			demoText.find('.demo-reload').on('click', function(){
			uploadInst2.upload();
		  });
		}
	 });

});



//查看砍价商品详情
function initdatas(){
	//加载时转圈圈
	//var index = top.layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
	$.ajax({
		url: "../../../../service",
		cache: false,
		data: {
			proc: "g_xmy.find_kanjiaById",
			para: "['" + username + "','" + secretkey + "',"+(kj_id*1)+"]"
		},
		dataType: "json",
		success: function(data) {
		//	console.log("查看砍价商品详情====="+JSON.stringify(data));
			if(data[0].TAG=='0'){
				top.layer.alert(""+data[0].MSG+"",function(index){
				   top.location.href="login.html";
				   layer.close(index);
				});
			}else if(data[0].msg=='读取接口失败,参数错误'||data.msg=='读取接口失败,参数错误'){
				top.layer.msg("修改失败，请检查您的网络环境!");
				console.log("读取接口失败,参数错误");
			}else if(data[0].TAG == 2){
				top.layer.msg(""+data[0].MSG+"");
			}else{
				$("#goods_name").val(data[0].GOODSNAME);		//商品名称
				$("#quanzh").val(data[0].WEIGHT);				//权重

				var a = $("#type").find("input");				//用户类型
				var userid="";
				userid=userid.split(",");
				for(var b=0;b<=a.length-1;b++){
					var s=$(a[b]).val();
					//console.log("用户类型s===="+s);
					for(var ss=0;ss<data.length;ss++){
						if(data[ss].USER_TYPE==s){
						$(a[b]).attr("checked","checked");
						}
					}
				}
				$("#Price_sign").val(data[0].GOODSPRICE);		//商品标签价格
				$("#Floor_price").val(data[0].GOODSFLOORPRICE);		//设置底价

				$("input[name='isshow_dj'][value='"+data[0].ISHOW_FLOORPRICE+"']").attr("checked",true);	//是否显示底价
				$("input[name='no_dj'][value='"+data[0].NOFLOORPRICE+"']").attr("checked",true);	//没有低价是否可以下单
				$("input[name='kj_bargain'][value='"+data[0].SELFKANJIA+"']").attr("checked",true);	//是否可以自己砍价
				$("input[name='Launch_Number'][value='"+data[0].ISFQ_MORE+"']").attr("checked",true);	//活动可发起次数
				if(data[0].ISFQ_MORE==0){
					$("#is_fq").show();
					$("#all_number").val(data[0].FQ_NUMBER);		//活动可发起次数
				}
				$("#goods_kucun").val(data[0].GOODSSTOCK);			//商品库存
				$("#stardate").val(data[0].BEGINTIME);				//开始时间
				$("#enddate").val(data[0].ENDTIME);					//结束时间
				$("#Cut_time").val(data[0].TIME_LIMIT);				//砍价时限
				$("#cut_number").val(data[0].TOTAL_NUMBER);			//可砍价总次数
				$("#each_number").val(data[0].EACH_NUMBER);			//每人可砍次数
				$("#fenx_biaoti").val(data[0].SHARE_TITLE);			//【分享】商品标题
				$("#fenx_miaosu").val(data[0].SHARE_DESCRIBE);		//【分享】商品描述

				Prize_img = data[0].SHARE_PICTURE;				//奖品图片
				if(Prize_img!=''&&Prize_img!=null){
					$("#Prize_img").css("display","block");
					$('#preview').attr('src', '../../../../advimg/'+Prize_img); //图片链接（base64）
				}else{
					$("#prize_picture").hide();
					$('#preview').css("display","block");
				}
				kanj_img = data[0].SHARE_KJPICTURE;				//【分享】砍价图片
				if(kanj_img!=''&&kanj_img!=null){
					$("#kanj_img").css("display","block");
					$('#preview2').attr('src', '../../../../advimg/'+kanj_img); //图片链接（base64）
				}else{
					$("#kanj_img").hide();
					$('#preview2').css("display","block");
				}

				$("#kj_biaoti").val(data[0].SHARE_KJTITLE);			//【分享】砍价标题
				$("#kj_miaosu").val(data[0].SHARE_KJDISCRIBE);		//【分享】砍价描述
				$("#kj_rule").val(decodeURIComponent(data[0].RULES));					//砍价规则设置
				$("#djs_words").val(data[0].COUNTDOWN_WORDS);		//倒计时前的文字
				$("#cut_words").val(data[0].KJ_WORDS);				//砍多少减多少文字

			//	console.log("概率===="+data[0].GAILV);
				if(data[0].GAILV>0){								//每次砍价概率
					find_kanjia_gl();

				}
				//二维码

				var erwm =  data[0].TWOCODE;
				if(erwm!=''&& erwm!=null){
					$("#show_twocode").css("display","block");
					$('#preview3').attr('src',erwm);
					$("#aa").hide();
				}
				//分享连接
				var fxlk = data[0].SHARE_HOOK;
				if(fxlk!=''&& fxlk!=null){
					$("#lj_nr").css("display","block");
					$('#lj_nr').attr('value',fxlk);
					$("#hook_up").hide();
				}

			}
		}
	});
}

//单独查概率
function find_kanjia_gl(){
	$.ajax({
		url: "../../../../service",
		cache: false,
		data: {
			proc: "g_xmy.find_kanjia_gl",
			para: "['" + username + "','" + secretkey + "',"+(kj_id*1)+"]"
		},
		dataType: "json",
		success: function(data) {
			$(".qujianitem").remove();
			for(var i=0;i<data.length;i++){

				gl +=  '<p class="margin_buttom10 qujianitem">'+
						 '<input type="text" class="form-control form-boxed width20 min_yuan" placeholder="" value="'+data[i].MIN_PRICE+'"/>元至'+
						 '<input type="text" class="form-control form-boxed width20 max_yuan" placeholder="" value="'+data[i].MAX_PRICE+'"/>元，'+
						 '概率<input type="text" class="form-control form-boxed width20 probability" placeholder="" value="'+data[i].PROBABILITY+'"/>%'+
						 '<P>';


			}
		//	console.log("gl==="+gl);
			$("#addqujian").before(gl);
		}
	});
}

//发起次数
function fqcs(){
	var Launch_Number = "";			//活动是否可以多次发起
	var radios4=document.getElementsByName("Launch_Number");
	for(var i=0;i<radios4.length;i++){
		if(radios4[i].checked==true){
			Launch_Number = radios4[i].value;
		}
	}
	if(Launch_Number==0){
		$("#is_fq").show();
	}else{
		$("#is_fq").hide();
	}
}

//生成二维码
function up_Twocode(){
	$("#show_twocode").show();
	var href_url=window.location.host;
	if(kj_id==0){
		$('#preview3').attr('src', 'http://bshare.optimix.asia/barCode?site=weixin&url=http://'+href_url+'/user/bargain_detail.html');
	}else{
		$('#preview3').attr('src', 'http://bshare.optimix.asia/barCode?site=weixin&url=http://'+href_url+'/user/bargain_detail.html?id='+kj_id);
	}
}

//生成【分享】连接
function get_fxlj(){
	$("#lj_nr").show();
var href_url=window.location.host;
	if(kj_id==0){
		$('#lj_nr').attr('value', 'http://'+href_url+'/user/bargain_detail.html');
	}else{
		$('#lj_nr').attr('value', 'http://'+href_url+'/user/bargain_detail.html?id='+kj_id);
	}
}



//添加或修改
function add_kanjia(){
	var goods_name = $("#goods_name").val().replace(/\s+/g, "");	//商品名称
	if(goods_name==""){
		layer.alert("请填写商品名称");
		return false;
	}
	var quanzh = $("#quanzh").val().replace(/\s+/g, "");			//权重
	if(quanzh==""){
		layer.alert("请填写权重");
		return false;
	}
	if(!(/^[0-9]{0,4}$/.test(quanzh))){
		layer.alert("权重填写格式有误！");
		return false;
	}

	var ac="";											//用户类型
	var count = 0;
	var a = $("#type").find("input");
	//console.log("用户类型=="+a);
	for(var b=0;b<a.length;b++){
		if(a[b].getAttribute("name")=="r"){
			if(a[b].checked==true){
				ac += a[b].value+",";
				count++;
			}
		}
	}
	var user_type = ac.substring(0,ac.length-1);
	console.log("用户类型user_type===="+user_type);
	if(user_type==""){
		layer.alert("请选择用户类型");
		return false;
	}

	var Price_sign = $("#Price_sign").val().replace(/\s+/g, "");    //签价格
	if(Price_sign==""){
		layer.alert("请填写签价格");
		return false;
	}
	if(isNaN(Price_sign) || Price_sign<0){
		layer.alert("签价格填写格式有误！");
		return false;
	}
	var Floor_price = $("#Floor_price").val().replace(/\s+/g, "");	//底价
	if(isNaN(Floor_price) || Floor_price<0){
		layer.alert("底价填写格式有误！");
		return false;
	}
	if(Number(Floor_price)>Number(Price_sign)){
		layer.alert("底价不得大于签价格！");
		return false;
	}
	var isshow_dj = "";			//是否显示底价
	var radios=document.getElementsByName("isshow_dj");
	for(var i=0;i<radios.length;i++){
		if(radios[i].checked==true){
			isshow_dj = radios[i].value;
		}
	}
	var no_dj = "";		//没有低价是否可以下单
	var radios2=document.getElementsByName("no_dj");
	for(var i=0;i<radios2.length;i++){
		if(radios2[i].checked==true){
			no_dj = radios2[i].value;
		}
	}
	var kj_bargain = "";		//是否可以自己砍价
	var radios3=document.getElementsByName("kj_bargain");
	for(var i=0;i<radios3.length;i++){
		if(radios3[i].checked==true){
			kj_bargain = radios3[i].value;
		}
	}
	var Launch_Number = "";			//活动是否可以多次发起
	var radios4=document.getElementsByName("Launch_Number");
	for(var i=0;i<radios4.length;i++){
		if(radios4[i].checked==true){
			Launch_Number = radios4[i].value;
		}
	}
	var stardate = document.getElementById("stardate").value;	  //活动开始时间
	var enddate = document.getElementById("enddate").value;	     //活动结束时间
	if(stardate==""){
		layer.alert("请选择开始时间");
		return false;
	}
	if(enddate==""){
		layer.alert("请选择结束时间");
		return false;
	}
	var d1 = new Date(stardate);
	var d2 = new Date(enddate);
	if(d1>d2){
		layer.alert("结束时间不能小于开始时间");
		return false;
	}

	var Cut_time = document.getElementById("Cut_time").value;	//砍价时限
	if(Cut_time==""){
		layer.alert("请填写砍价时限！");
		return false;
	}
	if(isNaN(Cut_time) || Cut_time<0){
		layer.alert("砍价时限填写格式有误！");
		return false;
	}
	if(Number(Cut_time)>24){
		layer.alert("砍价时限不得大于24小时！");
		return false;
	}
	var cut_number = document.getElementById("cut_number").value;	//可砍价总次数
	if(cut_number==""){
		layer.alert("请填写可砍价总次数！");
		return false;
	}
	if(isNaN(cut_number) || cut_number<0){
		layer.alert("可砍价总次数填写格式有误！");
		return false;
	}
	var each_number = document.getElementById("each_number").value;	//每人可砍次数
	if(each_number==""){
		layer.alert("请填写每人可砍次数！");
		return false;
	}
	if(isNaN(each_number) || each_number<0){
		layer.alert("每人可砍次数填写格式有误！");
		return false;
	}
	if(Number(each_number)>Number(cut_number)){
		layer.alert("每人可砍次数不得大于可砍价总次数！");
		return false;
	}
	var all_number = document.getElementById("all_number").value;	//活动可发起次数
	if(isNaN(all_number) || all_number<0){
		layer.alert("活动可发起次数填写格式有误！");
		return false;
	}
	var fenx_biaoti = document.getElementById("fenx_biaoti").value;		//【分享】商品标题
	if(fenx_biaoti==""){
		layer.alert("请填写【分享】商品标题！");
		return false;
	}
	var fenx_miaosu = document.getElementById("fenx_miaosu").value;		//【分享】商品描述
	if(fenx_miaosu==""){
		layer.alert("请填写【分享】商品描述！");
		return false;
	}
	var kj_biaoti = document.getElementById("kj_biaoti").value;		//【分享】砍价标题
	if(kj_biaoti==-1){
		layer.alert("请选择【分享】砍价标题！");
		return false;
	}
	var kj_miaosu = document.getElementById("kj_miaosu").value;		//【分享】砍价描述
	if(kj_miaosu==""){
		layer.alert("请填写【分享】砍价描述！");
		return false;
	}
	var kj_rule = document.getElementById("kj_rule").value;			//砍价规则
	if(kj_rule==""){
		layer.alert("请填写砍价规则！");
		return false;
	}
	kj_rule = encodeURIComponent(kj_rule);
	console.log("kj_rule.length===="+kj_rule.length);

	var djs_words = document.getElementById("djs_words").value;		//倒计时前的文字
	if(djs_words==""){
		layer.alert("请填写倒计时前的文字！");
		return false;
	}
	var cut_words = document.getElementById("cut_words").value;		//砍多少减多少文字
	if(cut_words==""){
		layer.alert("请填写砍多少减多少文字！");
		return false;
	}
	var goods_kucun = document.getElementById("goods_kucun").value; //商品库存
	if(goods_kucun==""){
		layer.alert("请填写商品库存！");
		return false;
	}
	if(isNaN(goods_kucun) || goods_kucun<0){
		layer.alert("商品库存填写格式有误！");
		return false;
	}

	var min_yuan = "";
	$(".min_yuan").each(function(e){
		min_yuan+=$(this).val()+",";
	});
	if(min_yuan==","){
		layer.alert("请填写每次砍价概率的最低价！");
		return false;
	}
	var min_yuan2 = min_yuan.substring(0,min_yuan.length-1);
	console.log("每次砍价概率，最低价===="+min_yuan2);
	var max_yuan = "";
	$(".max_yuan").each(function(e){
		max_yuan+=$(this).val()+",";
	});
	if(max_yuan==","){
		layer.alert("请填写每次砍价概率的最高价！");
		return false;
	}
	var max_yuan2 = max_yuan.substring(0,max_yuan.length-1);
	console.log("每次砍价概率，最高价===="+max_yuan2);
	var probability = "";
	var sum_pro=0;
	$(".probability").each(function(e){
		probability+=$(this).val()+",";
		sum_pro+=Number($(this).val());
	});
	if(probability==","){
		layer.alert("请填写每次砍价概率！");
		return false;
	}
	if(sum_pro>100){
		layer.alert("砍价概率总合不得大于100%！");
		return false;
	}
	var probability2 = probability.substring(0,probability.length-1);
	console.log("每次砍价概率===="+probability2+"//////"+sum_pro+"======="+typeof(sum_pro));

/*	if(Prize_img==undefined){		//奖品图片
		layer.alert("请上传奖品图片！");
		return false;
	}
	if(kanj_img==undefined){		//砍价图片
		layer.alert("请上传砍价图片！");
		return false;
	}
*/
	console.log("参数======"+username + "','" + secretkey + "','"+goods_name+"','"+quanzh+"','"+Price_sign+"','"+Floor_price+"','"+isshow_dj+"','"
				+no_dj+"','"+kj_bargain+"','"+Launch_Number+"','"+goods_kucun+"','"+stardate+"','"+enddate+"','"+Cut_time+"','"+cut_number+"','"
				+each_number+"','"+all_number+"','"+fenx_biaoti+"','"+fenx_miaosu+"','"+kj_biaoti+"','"+kj_miaosu+"','"+kj_rule+"','"
				+djs_words+"','"+cut_words+"','"+Prize_img+"','"+kanj_img+"','"+kj_id+"','"+min_yuan2+"','"+max_yuan2+"','"+probability2+"','"+user_type+"//////");



    top.layer.confirm('是否确认'+alertmsg+'该砍价活动？',{icon: 3,title:'提示信息'},function(index){
	//	var index = top.layer.msg(''+alertmsg+'中，请稍候',{icon: 16,time:false,shade:0.8});
		setTimeout(function(){
			$.ajax({
				url: "../../../../service",
				cache: false,
				data: {
					proc: "g_xmy.add_kanjia",
					para: "['" + username + "','" + secretkey + "','"+goods_name+"','"+quanzh+"','"+Price_sign+"','"+Floor_price+"','"+isshow_dj+"','"
								+no_dj+"','"+kj_bargain+"','"+Launch_Number+"','"+goods_kucun+"','"+stardate+"','"+enddate+"','"+Cut_time+"','"+cut_number+"','"
								+each_number+"','"+all_number+"','"+fenx_biaoti+"','"+fenx_miaosu+"','"+kj_biaoti+"','"+kj_miaosu+"','"+kj_rule+"','"
								+djs_words+"','"+cut_words+"','"+Prize_img+"','"+kanj_img+"','"+kj_id+"','"+min_yuan2+"','"+max_yuan2+"','"+probability2+"','"+user_type+"']"
				},
				dataType: "json",
				success: function(data) {
					console.log(JSON.stringify(data));
					top.layer.closeAll();	 //关闭所有转圈圈
					$.session.remove("kanjia_id");
					if(data[0].TAG=='0'){
						top.layer.alert(""+data[0].MSG+"",function(index){
						   top.location.href="login.html";
						//   layer.close(index);	//关闭转圈圈
					    });
					}else if(data[0].TAG=='2'){
						top.layer.msg(""+data[0].MSG+"");
					}else{
						top.layer.msg(""+data[0].MSG+"");
						re();
					}
				}
			});
		},1000);
	})

}

//全选
function check1(){
	var check = document.getElementById("usertype");
	var s = document.getElementById("type");
	var n = s.getElementsByTagName("input");
	for(i = 0;i < n.length;i++){//循环数组
		if (check.checked == false) {
			n[i].checked = false;
		} else{
			n[i].checked = true;
		}
	}
}

//返回
function re(){
	$.session.remove("kanjia_id");
	window.location.href="bargaining.html";
}
